package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.EmployeeEx;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 用于完成用户登录的方法
     *
     * @param employee
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {
        //1
        if (employee == null || StringUtils.isEmpty(employee.getUsername())
                || StringUtils.isEmpty(employee.getPassword())) {
            return R.error("用户名或密码不能为空");
        }
        // 根据页面提交的用户名username查询数据库  select * from employee where username= ?
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee exitEmp = employeeService.getOne(qw);

        //2、如果没有查询到则返回登录失败结果
        if (exitEmp == null) {
            return R.error("账户不存在!");
        }
        log.info("账号存在");

        //3、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (exitEmp.getStatus() == 0) {
            return R.error("账户已禁用!");
        }
        log.info("账号未禁用");

        // 数据库的 employee[密文]
        String password = exitEmp.getPassword();
        //将页面提交的密码[明文] password进行md5加密处理
        String pagePassword = employee.getPassword();
        pagePassword = DigestUtils.md5DigestAsHex(pagePassword.getBytes());

        //4.密码比对，如果不一致则返回登录失败结果
        if (!password.equals(pagePassword)) {
            // 比对失败, 返回code: 0 和 msg: 用户名和密码错误
            return R.error("用户名或密码错误");
        }
        log.info("密码正确");
        // 比对成功, 返回code: 1 和 data: 用户信息
        // 将用户数据存入会话中[session]
        //exitEmp.setPassword(null);
        session.setAttribute("employee", exitEmp);
        return R.success(exitEmp);
    }

    /**
     * 员工退出
     *
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        //清空Session 中保存的当前登录员工的id
        session.removeAttribute("employee");
        return R.success(null);
    }

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee, HttpSession session) {
        log.info("新增员工,员工信息: {}", employee.toString());
        //0.检查数据,哪些数据需要处理
        //0.1设置初始密码123456,需要进行md5加密处理
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        //0.2 status 不需要处理, 数据库默认是1
        //0.3 create_time 和 update_time ,设置当前系统时间 LocalDateTime.now()
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //0.4 create_user 和 update_user 创建人和修改人,应该是当前登陆人
        Employee loginUser = (Employee) session.getAttribute("employee");
        employee.setCreateUser(loginUser.getId());
        employee.setUpdateUser(loginUser.getId());*/

        //1.调用业务层保存employee数据
        boolean save = employeeService.save(employee);
        //2.返回结果
        if (save) {
            return R.success("新增员工成功!");
        } else {
            return R.error("保存失败!");
        }
    }

    /**
     * 员工信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> pageQuery(Integer page, Integer pageSize, String name) {

        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();

        //封装查询条件
        //添加过滤条件
        if (StringUtils.isNotEmpty(name)) {
            qw.like(Employee::getName, name);
        }
        //添加排序条件
        qw.orderByDesc(Employee::getUsername);

        // 进行带条件的分页查询, page(pageInfo,qw)
        employeeService.page(pageInfo, qw);

        // 通过pageInfo 对象获取分页结果  1.List<> 集合 2.总记录数
        /*List<Employee> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        Map data = new HashMap();
        data.put("reconds", records);
        data.put("total", total);
        return R.success(data);*/

        return R.success(pageInfo);
    }

    /**
     * 根据id修改员工信息(启用/禁用)
     *
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee, HttpSession session) {
        log.info(employee.toString());

        /*Employee LoginUser = (Employee) session.getAttribute("employee");
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(LoginUser.getId());*/

        employeeService.updateById(employee);
        return R.success("员工信息修改成功!");
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查询到对应的员工消息");
    }

    //用于文件下载
    @GetMapping("/export")
    public void exportEmployee(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition",
                "attachment; filename=employee.xlsx"); //指定文件下的名称！！


        List<Employee> list = employeeService.list();
        List<EmployeeEx> collect = list.stream().map((one) -> {

            EmployeeEx employeeEx = new EmployeeEx();
            BeanUtils.copyProperties(one, employeeEx);

            //设置id
            employeeEx.setId(one.getId().toString());

            //更改了名字
            String name = employeeService.getById(one.getCreateUser()).getName();
            employeeEx.setCreateUser(name);
            String nameU = employeeService.getById(one.getUpdateUser()).getName();
            employeeEx.setUpdateUser(nameU);

            //更改性别
            if ("0".equals(one.getSex())) {
                employeeEx.setSex("女");
            } else {
                employeeEx.setSex("男");
            }

            //启用禁用
            if (0 == (one.getStatus())) {
                employeeEx.setStatus("离职");
            } else {
                employeeEx.setStatus("在职");
            }

            return employeeEx;
        }).collect(Collectors.toList());
        try {
            EasyExcel.write(response.getOutputStream(), EmployeeEx.class).sheet("模板").doWrite(collect);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
